package cn.edu.zut.hkxy.util;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class HTMLUtils {
    public static String htmlEncode(String s) {
        if (s == null) {
            return "";
        }
        String source=s.replace("\n","<br>");
        String html = "";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < source.length(); i++) {
            char c = source.charAt(i);
            switch (c) {
                case '<':
                    buffer.append("&lt;");
                    break;
                case '>':
                    buffer.append("&gt;");
                    break;
                case '&':
                    buffer.append("&amp;");
                    break;
                case '"':
                    buffer.append("&quot;");
                    break;
                case 13:
                    break;
                default:
                    buffer.append(c);
            }
        }
        html = buffer.toString();
        return html;
    }

    public static String escape(String source) throws ScriptException {
        ScriptEngineManager scriptEngineManager=new ScriptEngineManager();
        ScriptEngine engine = scriptEngineManager.getEngineByExtension("js");
        Object obj = engine.eval("encodeURIComponent("+source+")");
        return (String)obj;
    }
}
